<template>
  <!-- 管理员布局 -->
  <el-container v-if="isAdmin" class="admin-layout">
    <!-- 左侧边栏 -->
    <ManageSider />

    <!-- 右侧内容区 -->
    <el-container direction="vertical">
      <!-- 顶部导航栏 -->
      <ManageHeader />

      <!-- 主内容区 -->
      <el-main class="admin-main-content">
        <div class="admin-container">
          <div class="action-bar">
            <h1>订单管理</h1>
            <el-button
                type="danger"
                @click="handleBatchDelete"
                icon="el-icon-delete"
                :disabled="selectedOrders.length === 0"
            >
              批量删除
            </el-button>
          </div>

          <el-table
              :data="paginatedOrders"
              style="width: 100%"
              stripe
              @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="订单ID" width="100"></el-table-column>
            <el-table-column prop="userName" label="下单用户" width="120"></el-table-column>
            <el-table-column prop="canteenName" label="餐厅名称" width="150"></el-table-column>
            <el-table-column prop="seatId" label="餐桌号" width="100"></el-table-column>
            <el-table-column prop="status" label="订单状态" width="100">
              <template #default="{row}">
                <el-tag :type="getStatusTagType(row.status)">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderAmount" label="订单金额" width="100" align="right">
              <template #default="{row}">
                ¥{{ row.orderAmount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="orderDate" label="下单时间" width="180">
              <template #default="{row}">
                {{ formatDate(row.orderDate) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button
                    type="text"
                    @click="viewOrderDetail(scope.row)"
                    icon="el-icon-view"
                >
                  详情
                </el-button>
                <el-button
                    type="text"
                    @click="handleCancel(scope.row)"
                    icon="el-icon-close"
                    style="color: #f56c6c"
                    v-if="scope.row.status === '待支付'"
                >
                  取消
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :total="totalOrders"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
              style="margin-top: 20px;"
          />
        </div>
      </el-main>
    </el-container>
  </el-container>

  <!-- 普通用户布局 -->
  <div v-else>
    <NormalHeader />
    <div class="permission-denied">
      <h1>管理员功能暂时不对您开放</h1>
    </div>
  </div>

  <!-- 订单详情弹框 -->
  <el-dialog v-model="dialogVisible" title="订单详情" width="50%">
    <div v-if="orderDetail" class="order-detail">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{ orderDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="下单用户">{{ orderDetail.userName }}</el-descriptions-item>
        <el-descriptions-item label="餐厅名称">{{ orderDetail.canteenName }}</el-descriptions-item>
        <el-descriptions-item label="餐桌号">{{ orderDetail.seatId }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusTagType(orderDetail.status)">
            {{ orderDetail.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ orderDetail.orderAmount.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ formatDate(orderDetail.orderDate) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间" v-if="orderDetail.payDate">
          {{ formatDate(orderDetail.payDate) }}
        </el-descriptions-item>
      </el-descriptions>

      <div class="order-items" v-if="orderDetail.items && orderDetail.items.length">
        <h3 style="margin: 20px 0 10px;">订单菜品</h3>
        <el-table :data="orderDetail.items" border>
          <el-table-column prop="dishName" label="菜品名称"></el-table-column>
          <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
          <el-table-column prop="price" label="单价" width="100" align="right">
            <template #default="{row}">
              ¥{{ row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120" align="right">
            <template #default="{row}">
              ¥{{ (row.price * row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage, ElMessageBox } from "element-plus";
import { GetOrders, DeleteOrder, GetOrderDetail } from "@/api";
import dayjs from 'dayjs';
import NormalHeader from "@/components/NormalHeader.vue";
import ManageSider from "@/components/ManageSider.vue";
import ManageHeader from "@/components/ManageHeader.vue";

export default {
  name: "ManageOrder",
  components: {
    NormalHeader,
    ManageSider,
    ManageHeader
  },
  data() {
    return {
      isAdmin: false,
      orders: [],
      pageSize: 8,
      currentPage: 1,
      totalOrders: 0,
      selectedOrders: [],
      dialogVisible: false,
      orderDetail: null
    };
  },
  computed: {
    paginatedOrders() {
      return this.orders;
    }
  },
  async mounted() {
    await this.checkAdminPermission();
    if (this.isAdmin) {
      await this.fetchOrders();
    }
  },
  methods: {
    async checkAdminPermission() {
      const userType = localStorage.getItem("type");
      this.isAdmin = userType === "0";
    },
    async fetchOrders() {
      try {
        const { data } = await GetOrders(this.currentPage, this.pageSize);
        if (data.code === 200) {
          this.orders = Array.isArray(data.data.orders) ? data.data.orders : [];
          this.totalOrders = data.data.total || 0;
        } else {
          ElMessage.error(data.message || "获取订单列表失败");
        }
      } catch (error) {
        ElMessage.error("获取订单列表失败");
        console.error(error);
      }
    },
    formatDate(dateString) {
      if (!dateString) return '-';
      return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
    },
    getStatusTagType(status) {
      switch (status) {
        case '已完成': return 'success';
        case '待支付': return 'warning';
        case '已取消': return 'info';
        default: return '';
      }
    },
    async viewOrderDetail(order) {
      try {
        const { data } = await GetOrderDetail(order.id);
        if (data.code === 200) {
          this.orderDetail = data.data;
          this.dialogVisible = true;
        } else {
          ElMessage.error(data.message || "获取订单详情失败");
        }
      } catch (error) {
        ElMessage.error("获取订单详情失败");
        console.error(error);
      }
    },
    handleSelectionChange(selection) {
      this.selectedOrders = selection;
    },
    async handleBatchDelete() {
      if (this.selectedOrders.length === 0) {
        ElMessage.warning("请至少选择一条订单");
        return;
      }

      try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${this.selectedOrders.length} 条订单吗?`,
            '提示',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        );

        const ids = this.selectedOrders.map(order => order.id).join(',');
        const { data } = await DeleteOrder(ids);

        if (data.code === 200) {
          ElMessage.success("删除成功");
          await this.fetchOrders();
          this.selectedOrders = [];
        } else {
          ElMessage.error(data.message || "删除失败");
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error("删除失败");
        }
      }
    },
    // async handleCancel(modules) {
    //   try {
    //     await ElMessageBox.confirm(
    //         `确定要取消订单 ${modules.id} 吗?`,
    //         '提示',
    //         { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    //     );
    //
    //     const { data } = await CancelOrder(modules.id);
    //
    //     if (data.code === 200) {
    //       ElMessage.success("订单已取消");
    //       await this.fetchOrders();
    //     } else {
    //       ElMessage.error(data.message || "取消失败");
    //     }
    //   } catch (error) {
    //     if (error !== 'cancel') {
    //       ElMessage.error("取消失败");
    //     }
    //   }
    // },
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchOrders();
    }
  }
};
</script>

<style scoped>
.admin-layout {
  height: 100vh;
}

.admin-main-content {
  padding: 20px;
  height: 100vh;
  overflow-y: auto;
  margin-left: 200px; /* 等于侧边栏宽度 */
  background-color: #f5f7fa;
}

.admin-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.permission-denied {
  text-align: center;
  padding: 100px 0;
}

.order-detail {
  line-height: 2;
}

.order-items {
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .admin-container {
    padding: 15px;
  }

  .admin-main-content {
    margin-left: 0;
  }
}
</style>
